<?php

require_once 'smarty3/libs/Smarty.class.php';

class CI_Template extends Smarty {

    private $_ci_instance;
    private $_template_folder = 'default';

    public function __construct() {
        parent::__construct();
        $this->auto_literal = false;
        $this->compile_dir = APPPATH . 'compile';
        $this->cache_dir = APPPATH . 'cache';
        $this->_ci_instance = & get_instance();
        $this->set_template_folder();
    }

    public function get_template_folder() {
        return TEMPLATEPATH . $this->_template_folder . DIRECTORY_SEPARATOR;
    }

    public function set_template_folder($folder = 'default') {
        if (is_dir(TEMPLATEPATH . $folder)) {
            $this->_template_folder = $folder;
            $this->setTemplateDir(TEMPLATEPATH . $this->_template_folder . DIRECTORY_SEPARATOR);
        }
    }

    public function fetch($template = null, $cache_id = null, $compile_id = null, $parent = null, $display = false) {
        global $template_folder;

        if (is_null($template)) {
            $template = $this->_ci_instance->router->directory . $this->_ci_instance->router->class . ($this->_ci_instance->router->method == 'index' ? '' : '.' . $this->_ci_instance->router->method) . '.tpl';
        }

        if (!is_file(TEMPLATEPATH . $this->_template_folder . "/" . $template)) {
            show_error("File '" . $this->_template_folder . '/' . $template . "' not found");
            exit;
        }

        $this->assign('template', array(
            "url" => $this->_ci_instance->config->item('base_url') . $template_folder . '/' . $this->_template_folder . '/',
            "name" => $this->_template_folder
        ));

        return parent::fetch($template, $cache_id, $compile_id, $parent, $display);
    }

    public function display($template = null, $cache_id = null, $compile_id = null, $parent = null) {
        global $BM;

        $output = $this->fetch($template, $cache_id, $compile_id, $parent);
        $BM->mark('total_execution_time_end');

        $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
        $output = preg_replace('/\[ELAPSED_TIME\]/i', $elapsed, $output);

        $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage() / 1024, 2) . 'KB';
        $output = preg_replace('/\[MEM_USAGE\]/i', $memory, $output);

        echo $output;
    }

}

?>